import { Effect, Reducer } from 'umi';
import { message } from 'antd';
import { MenuItem } from '@/pages/Base/Menu/data';
import { fetchAllMenu, addMenu, updateMenu, deleteMenus } from '@/services/menuApis';
import { querySysDict } from '@/services/systemApis';
import { DataItem } from './common';
import { TradeResult } from './connect';

export interface MenuModelStateEx {
  menuList?: MenuItem[];
  total?: number;
  pageSize?: number;
  menuTypeData?: DataItem[],
  menuActionData?: DataItem[],
  statusData?: DataItem[],
  hideInMenuData?: DataItem[],
}

export interface MenuModelType {
  namespace: 'menus';
  state: MenuModelStateEx;
  effects: {
    fetchMenuInitParams: Effect;
    fetchAllMenu: Effect;
    addMenu: Effect;
    updateMenu: Effect;
    deleteMenus: Effect;
  };
  reducers: {
    updateState: Reducer<MenuModelStateEx>;
  };
}

const MenuModel: MenuModelType = {
  namespace: 'menus',
  state: {
    menuList: [],
    total: 0,
    pageSize: 10,
    statusData: [
      {
        key: '0',
        value: '生效'
      },
      {
        key: '1',
        value: '失效'
      }
    ],
    hideInMenuData: [
      {
        key: '0',
        value: '显示'
      },
      {
        key: '1',
        value: '隐藏'
      }
    ],
  },
  effects: {
    *fetchMenuInitParams({ payload }, sagaEffects) {
      const { all, call, put } = sagaEffects;
      try {
        const [ menuTypeResponse, menuActionResponse, statusResponse ] = yield all([
          call(querySysDict, {
            dictName: 'menuType'
          }),
          call(querySysDict, {
            dictName: 'menuAction'
          }),
          call(querySysDict, {
            dictName: 'status'
          })
        ]);
        console.info(menuTypeResponse);
        console.info(menuActionResponse);
        console.info(statusResponse);
        const systemSuccess =  menuTypeResponse.success;
        const clusterSuccess =  menuActionResponse.success;
        if (!systemSuccess || !clusterSuccess) {
          if (!systemSuccess) {
            message.error(`${menuTypeResponse.errorCode}:${menuTypeResponse.errorMsg}`); // 打印错误信息
          }
          if (!clusterSuccess) {
            message.error(`${menuActionResponse.errorCode}:${menuActionResponse.errorMsg}`); // 打印错误信息
          }
        } else {
          // const systemData = systemResponse.result.rows;
          // const clusterData = clusterResponse.result.rows;
          const result  = {
            menuTypeData: [...menuTypeResponse.result],
            menuActionData: [...menuActionResponse.result],
          };
          console.info(result);
          yield put({ type: 'updateState', payload: result });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fetchAllMenu({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(fetchAllMenu, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          // 通讯成功取出数据
          const { result } = response;
          // 更新表格数据
          yield put({ type: 'updateState', payload: result });
        }
      } catch(e) {
        console.info(e);
        message.error('数据获取失败'); // 打印错误信息
      }
    },
    *addMenu({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response = yield call(addMenu, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          message.success('新增成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('新增失败'); // 打印错误信息
        return false;
      }
    },
    *updateMenu({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response = yield call(updateMenu, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          message.success('更新成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('更新失败'); // 打印错误信息
        return false;
      }
    },
    *deleteMenus({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response = yield call(deleteMenus, payload);
        // console.log(JSON.stringify(response));
        // yield call(delay, 3000);
        const { success } = response;
        if (success) {
          message.success('删除成功');
          // 刷新表格
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('删除失败'); // 打印错误信息
        return false;
      }
    }
  },
  reducers: {
    updateState(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        ...payload
      }
    },
  },
}

export default MenuModel;